<template>
  <div v-show="!pageData.showDayCheckView" class="ver-layout">
    <!--  表单  -->
    <el-form ref="formRef" :model="pageData.formData" inline size="small">
      <el-form-item label="姓名" class="form-item-view" prop="userName">
        <el-select v-model="pageData.formData.userName" filterable multiple clearable placeholder="请选择">
          <el-option v-for="(item,index) in pageData.userNameOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="员工编号" class="form-item-view" prop="userCode">
        <el-select v-model="pageData.formData.userCode" filterable multiple clearable placeholder="请选择">
          <el-option v-for="(item,index) in pageData.userCodeOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="考勤类型" class="form-item-view" prop="dayOffType">
        <el-select v-model="pageData.formData.dayOffType" filterable multiple clearable placeholder="请选择">
          <el-option v-for="(item,index) in pageData.dayOffTypeOptions"
                     :key="index"
                     :label="item.label"
                     :value="item.value"
                     :disabled="item.disabled"/>
        </el-select>
      </el-form-item>
      <div class="hor-layout-side-center"
           style="padding-bottom: 10px;margin-bottom: 20px;margin-right: 50px;border-bottom: 1px solid #909399">
        <div class="hor-layout">
          <el-button type="success" size="small" @click="()=>emit('uploadClick')">上传考勤表格</el-button>
        </div>
        <div class="hor-layout">
          <el-button type="default" size="small" @click="resetFormData"
                     :disabled="pageData.tableLoading">
            重置
          </el-button>
          <el-button type="primary" size="small" @click="queryFormData"
                     :disabled="pageData.tableLoading">
            查询
          </el-button>
        </div>
      </div>
    </el-form>
    <!--  表格    -->
    <el-table :data="computedData.tableData" height="530px" border size="small"
              highlight-current-row v-loading="pageData.tableLoading" :cell-style="cellStyle"
              @cell-click="cellClick1">
      <el-table-column v-if="computedData.tableHeader.length" type="index" label="序号" width="50px"
                       fixed="left"></el-table-column>
      <el-table-column v-for="(headerItem,headerIndex) in computedData.tableHeader"
                       :prop="headerItem"
                       :label="headerItem"
                       :fixed="headerItem=='员工姓名'?'left':false"
                       :min-width="getTableWidth(headerItem)"
                       :show-overflow-tooltip="true"/>
    </el-table>
  </div>
  <dayCheckTableView v-if="pageData.showDayCheckView"
                     @backClick="pageData.showDayCheckView=false"
                     :selectDayData="pageData.selectDayData"/>
</template>

<script setup lang="ts">
import {computed, reactive, ref, watch} from "vue";
import {dayOffType} from "@/utils/data_utils.ts";
import type {FormInstance} from "element-plus";
import dayCheckTableView from "@/views/attendance/components/dayCheckTableView.vue";

const emit = defineEmits(['uploadClick']);

interface Props {
  parentPageData?: Object;//
}

const props = withDefaults(defineProps<Props>(), {});

const formRef = ref<FormInstance>();

const pageData = reactive({
  showDayCheckView: false,
  selectDayData: {},
  tableLoading: false,
  filterData: {},
  formData: {
    userName: [],
    userCode: [],
    dayOffType: [],
  },
  userNameOptions: [],
  userCodeOptions: [],
  dayOffTypeOptions: Object.keys(dayOffType).map(item => {
    return {
      label: item,
      value: item,
      disabled: false
    }
  }),
})

const computedData = computed(() => {
  let {userName, userCode, dayOffType} = pageData.filterData
  let userNameStr = userName && userName.join(',')
  let userCodeStr = userCode && userCode.join(',')
  let dayOffTypeStr = dayOffType && dayOffType.join(',')
  let tableData = JSON.parse(JSON.stringify(props.parentPageData.tableData))
  // console.log("computedData==", tableData, userNameStr, userCodeStr, dayOffTypeStr)
  let filterTableData1 = tableData.filter(tableItem => {
    let tableItemValueList = Object.values(tableItem)
    let userNameFilter = userNameStr ? tableItemValueList.find(tableItemValue => userNameStr.includes(tableItemValue)) : true
    let userCodeFilter = userCodeStr ? tableItemValueList.find(tableItemValue => userCodeStr.includes(tableItemValue)) : true
    let dayOffTypeFilter = dayOffTypeStr ? tableItemValueList.find(tableItemValue => dayOffTypeStr.includes(tableItemValue)) : true
    return userNameFilter && userCodeFilter && dayOffTypeFilter
  })
  // console.log("computedData==filterTableData1", filterTableData1)
  let filterTableData2 = filterTableData1.map(tableItem => {
    Object.keys(tableItem).forEach(tableItemKey => {
      //1日 | 1日_1
      if (tableItemKey.includes('日') && !tableItemKey.includes("_")) {
        let allTableItem = tableData.find(allTableItem => allTableItem['员工编号'] == tableItem['员工编号'])
        if (['上午', '下午'].includes(tableItem[`${tableItemKey}_1`])) {
          tableItem[tableItemKey] = `${tableItem[tableItemKey]}/${tableItem[`${tableItemKey}_1`]}`
        }
      }
      let tableItemDayOff = tableItem[tableItemKey].includes("/") ? tableItem[tableItemKey].split("/")[0] : tableItem[tableItemKey]
      if (tableItemKey.includes('日') && dayOffTypeStr && !dayOffTypeStr.includes(tableItemDayOff)) {
        tableItem[`${tableItemKey}_0`] = tableItem[tableItemKey]
        tableItem[tableItemKey] = ''
      }
    })
    return tableItem
  })
  // console.log("computedData==filterTableData2", filterTableData2)
  return {
    tableData: filterTableData2,
    tableHeader: props.parentPageData.tableHeader,
  }
})

//
const haveFilterData = computed(() => {
  return Object.values(pageData.filterData).filter(item => item && item.length).length
})

const getTableWidth = (item) => {
  let unitWidth = item.length < 4 ? 30 : 20
  if (item.includes("日")) return "70px"
  return `${item.length * unitWidth}px`
}

//单元格样式
const cellStyle = (data) => {
  if (data.columnIndex == 1) {
    return {
      color: 'blue',
      textDecoration: 'underline',
    }
  }
  if (data.columnIndex <= 4) return {color: '#606266'}
  let dayOffKey = props.parentPageData.tableHeader.length > data.columnIndex - 1 && props.parentPageData.tableHeader[data.columnIndex - 1]
  let cellValue = data.row[dayOffKey]
  let isHalfDayOff = cellValue && cellValue.includes("/")
  // console.log("cellStyle==", props.parentPageData.tableHeader, data.columnIndex, cellValue)
  // console.log("cellStyle==", cellValue)
  if (!haveFilterData.value) {
    return {color: '#606266', backgroundColor: isHalfDayOff ? '#ffb9b9' : ''}
  }
  if (cellValue && data.columnIndex > 4) {
    return {
      color: dayOffType[cellValue] || '#606266',
      backgroundColor: isHalfDayOff ? '#ffb9b9' : ''
    }
  }
  return {color: '#606266'}
}

//单元格点击事件
const cellClick1 = (row, column) => {
  console.log("cellClick", row, column)
  if (column.label == '员工姓名') {
    pageData.showDayCheckView = true
    pageData.selectDayData = row
  }
}

const resetFormData = () => {
  formRef.value?.resetFields()
  queryFormData()
}

const queryFormData = () => {
  pageData.tableLoading = true
  setTimeout(() => {
    pageData.filterData = JSON.parse(JSON.stringify(pageData.formData))
    pageData.tableLoading = false
  }, 300)
  // console.log("queryFormData", JSON.stringify(props.parentPageData.tableData))
}

//监听
watch(props.parentPageData, (data) => {
  pageData.userNameOptions = data.tableData.map(tableItem => {
    return {
      label: tableItem['员工姓名'],
      value: tableItem['员工姓名']
    }
  })
  pageData.userCodeOptions = data.tableData.map(tableItem => {
    return {
      label: tableItem['员工编号'],
      value: tableItem['员工编号']
    }
  })
  //更新考勤类型里面的可选属性
  let totalSeries = {}
  data.tableHeader.filter(item => item.includes("日")).forEach(dayName => {
    data.tableData.forEach(userItem => {
      let dayOff = userItem[dayName]
      totalSeries[dayOff] = dayOff
    })
  })
  let totalSeriesKeys = Object.keys(totalSeries)
  // console.log("totalSeriesKeys==", data.tableHeader, totalSeries, totalSeriesKeys)
  pageData.dayOffTypeOptions = pageData.dayOffTypeOptions.map(item => {
    item.disabled = !totalSeriesKeys.includes(item.value)
    return item
  })
  pageData.dayOffTypeOptions.sort((a, b) => a.disabled - b.disabled)
  // console.log("pageData.dayOffTypeOptions==", JSON.stringify(pageData.dayOffTypeOptions))
}, {
  immediate: true,
})
</script>

<style scoped>
.form-item-view {
  width: 30%;
}

/deep/ .el-table .current-row > td {
  background-color: #10aedd !important; /* 自定义颜色 */
}
</style>